package com.example.smart.demo_imageview;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private EditText et_path;
    private ImageView iv;
    private Handler handler=new Handler(){
        public void handleMessage(android.os.Message msg){
            switch (msg.what){
                case 1:
                    Bitmap bitmap=(Bitmap)msg.obj;
                    iv.setImageBitmap(bitmap);
                    break;
                case 2:
                    Toast.makeText(MainActivity.this,"网络连接失败",Toast.LENGTH_SHORT).show();
            }

        }
    };
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_path=(EditText)findViewById(R.id.et_path);
        iv=(ImageView)findViewById(R.id.iv);
    }
    public void find(View view){
        final String path=et_path.getText().toString().trim();
        if (TextUtils.isEmpty(path)){
            Toast.makeText(this,"路径不能为空",Toast.LENGTH_SHORT).show();
            return;
        }

        new Thread(){
            public void run(){
                try {
                    URL url=new URL(path);
                    HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                    int code=connection.getResponseCode();
                    if (code == 200){
                        Log.e("TEST","链接成功,开始读取数据");
                        InputStream is=connection.getInputStream();
                        Bitmap bitmap= BitmapFactory.decodeStream(is);
                        Message msg=new Message();
                        msg.obj=bitmap;
                        msg.what=1;
                        handler.sendMessage(msg);
                        //iv.setImageBitmap(bitmap);
                        is.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg=new Message();
                    msg.obj="EEEEEEEEE";
                    msg.what= 2;
                    handler.sendMessage(msg);
                    Log.e("TEST","链接失败");
                }
            }
        }.start();


    }
}
